//
//  HMStackView.swift
//  GuoGuo
//
//  Created by 艾小新 on 16/8/15.
//  Copyright © 2016年 xiaoxin. All rights reserved.
//  ComposeTabBar底部

import UIKit
@available(iOS 9.0, *)

/// 按钮标志枚举
///
/// - Picture:  图片
/// - Mention:  @
/// - Trend:    话题
/// - Emoticon: @表情
/// - Add:      添加附件
enum HMStackViewModel : Int {
    case Picture = 0,Mention, Trend, Emoticon, Add
}

class HMStackView: UIStackView {
    
    
    // 修改图标
    var isSystemKeyboard :Bool = true {
        
        didSet {
            
            var imageNamed = "compose_keyboardbutton_background"
            // 拿到这个button
            let button = viewWithTag(HMStackViewModel.Emoticon.rawValue) as! UIButton
            
            if isSystemKeyboard {
                // 是系统键盘,显示笑脸
                imageNamed = "compose_emoticonbutton_background"
            }
            button.setImage(UIImage(named: imageNamed), forState: UIControlState.Normal)
            button.setImage(UIImage(named: "\(imageNamed)_highlighted"), forState: UIControlState.Highlighted)
        }
        
    }
    

    var composeCallBack: ((type:HMStackViewModel)->())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        // 设置大小相等并且填充父控件
        distribution = .FillEqually
        
        addChildButton("compose_toolbar_picture", type: .Picture)
        addChildButton("compose_mentionbutton_background", type: .Mention)
        addChildButton("compose_trendbutton_background", type: .Trend)
        addChildButton("compose_emoticonbutton_background", type: .Emoticon)
        addChildButton("compose_add_background", type: .Add)
    }
    
    /// 添加子按钮的方法
    ///
    /// - parameter imageNamed: <#imageNamed description#>
    private func addChildButton(imageNamed: String, type: HMStackViewModel){
        // 初始化按钮
        let button = UIButton()
        // 设置按钮的tag 以区分是哪个按钮点击了
        button.tag = type.rawValue
        
        // 添加监听事件
        button.addTarget(self, action: #selector(HMStackView.clickButton(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置不同状态的图片
        button.setImage(UIImage(named: imageNamed), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "\(imageNamed)_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置背景图
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "compose_toolbar_background"), forState: UIControlState.Highlighted)
        
        // UIStackView添加子控件的方式
        addArrangedSubview(button)
    }

    @objc func clickButton(btn: UIButton) {
        
        composeCallBack?(type: HMStackViewModel(rawValue: btn.tag)!)
    }
    
    

}
